/**
 * Todo的model
 */

import xs, { Stream } from 'xstream';
import { TodoAction, TodoReducer, TodoState } from '../../types';

/**
 * Todo的model方法
 * @param actions 
 */
export default function model(actions : TodoAction) : Stream<TodoReducer> {
    // 开始编辑
    const startEditReducer$ = actions.startEdit$
        .mapTo<TodoReducer>((state : TodoState) => ({...state, editing: true}));

    // 结束编辑
    const doneEditReducer$ = actions.doneEdit$
        .map<TodoReducer>(content => (state : TodoState) => ({...state, title: content, editing: false}));

    // 取消编辑
    const cancelEditReducer$ = actions.cancelEdit$
        .mapTo<TodoReducer>((state : TodoState) => ({...state, editing: false}));

    // 切换勾选状态
    const toggleReducer$ = actions.toggle$
        .map<TodoReducer>(isToggled => (state : TodoState) => ({...state, completed: isToggled}));

    // 删除
    const destroyReducer$ = actions.destroy$
    .mapTo<TodoReducer>((state : TodoState) => void 0);

    // 返回合并过的reducer
    return xs.merge(
        startEditReducer$,
        doneEditReducer$,
        cancelEditReducer$,
        toggleReducer$,
        destroyReducer$
    );
}